package crontab

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"longmen/server/config/global"
	"longmen/server/pkg/common/services"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	"net/http"
	"os"
	"time"
)

type Recharge6tResponse struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data Data   `json:"data"`
}

type Data struct {
	Content      []RechargeInfo `json:"content"`
	PageNumber   int            `json:"pageNumber"`
	PageSize     int            `json:"pageSize"`
	TotalPages   int            `json:"totalPages"`
	TotalRecords int            `json:"totalRecords"`
}

type RechargeInfo struct {
	Account       string  `json:"account"`
	TotalRecharge float64 `json:"totalRecharge"`
}

func (s *Script) GetBindUsers(startTime, endTime time.Time) {
	ctx := context.Background()

	user6tBinds, err := db_main.GetAll6tBindUsers()
	if err != nil {
		log.Printf("获取绑定的用户列表失败: %v", err)
		return
	}
	log.Printf("共获取 %d 个用户", len(user6tBinds))

	user6tBindMap := map[string]*models_main.DbUserBinding6taccount{}
	for _, user6tBind := range user6tBinds {
		user6tBindMap[user6tBind.Account] = user6tBind
	}

	recharge6tResp, err := fetchGet6tChargeAccounts(ctx, startTime, endTime)
	if err != nil {
		log.Printf("获取6t充值的用户列表失败: %v", err)
		return
	}

	if len(recharge6tResp.Data.Content) == 0 {
		log.Printf("6t充值的用户列表为空: %v", len(recharge6tResp.Data.Content))
		return
	}

	sendTicketUserIds := make([]int64, 0)
	for _, echarge6t := range recharge6tResp.Data.Content {
		if _, ok := user6tBindMap[echarge6t.Account]; ok {
			sendTicketUserIds = append(sendTicketUserIds, int64(user6tBindMap[echarge6t.Account].UID))
		}
	}

	successUids := s.BatchSendTicket(sendTicketUserIds, 1)

	// 更新发放状态
	if err := global.GetX().Model(&models_main.DbUserBinding6taccount{}).Where("uid in ? and status != ?", successUids, 1).Updates(map[string]interface{}{
		"status":           1,
		"first_check_time": time.Now(),
	}).Error; err != nil {
		log.Printf("更新绑定6t账号的状态失败: %v", err)
		return
	}
}

func fetchGet6tChargeAccounts(ctx context.Context, startTime, endTime time.Time) (*Recharge6tResponse, error) {
	const pageSize = 200
	pageNumber := 1
	var allContent []RechargeInfo

	for {
		domain := global.Config.GetString("live6turl")
		fmt.Println(domain, "xxx")
		url := fmt.Sprintf("%v/devApi/pay/balance/record/accountTotalRechargePageList", domain)
		payload := map[string]interface{}{
			"startTime":   startTime.Format(time.DateTime),
			"endTime":     endTime.Format(time.DateTime),
			"currentPage": pageNumber,
			"pageSize":    pageSize,
			"sign":        "WgTkFzJ0X0j5q+L1ZRcjtwVTV3K71gGSBI1Fy+N0dIQ=",
		}
		fmt.Println(payload, "xxxxx")
		jsonData, err := json.Marshal(payload)
		if err != nil {
			return nil, err
		}

		req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData))
		if err != nil {
			return nil, err
		}

		req.Header.Set("Content-Type", "application/json")

		client := &http.Client{}
		resp, err := client.Do(req)
		if err != nil {
			return nil, err
		}
		defer resp.Body.Close()

		body, err := io.ReadAll(resp.Body)
		if err != nil {
			return nil, err
		}

		var respData Recharge6tResponse
		if err := json.Unmarshal(body, &respData); err != nil {
			return nil, err
		}

		if respData.Code != 0 {
			log.Printf("请求失败 code: %v, msg: %v", respData.Code, respData.Msg)
			break
		}

		allContent = append(allContent, respData.Data.Content...)

		if pageNumber >= respData.Data.TotalPages {
			break
		}
		pageNumber++
	}
	log.Printf("充值记录用户: %v", allContent)
	log.Printf("共拉取 %d 条充值记录", len(allContent))

	return &Recharge6tResponse{
		Code: 0,
		Msg:  "成功",
		Data: Data{
			Content: allContent,
		},
	}, nil
}

func Check6t() {

	service := &services.Service{global.GetX()}
	service.InitLiveCallBackServer()
	s := &Script{
		Service: service,
	}

	var startTime, endTime time.Time
	const layout = "2006-01-02"

	configStartTime := global.Config.GetString("live6tStartTime")
	configEndTime := global.Config.GetString("live6tEndTime")
	if len(os.Args) >= 4 {
		var err error
		startTime, err = time.ParseInLocation(layout, os.Args[2], time.Local)
		if err != nil {
			log.Printf("解析 startTime 失败: %v", err)
			return
		}
		endTime, err = time.ParseInLocation(layout, os.Args[3], time.Local)
		if err != nil {
			log.Printf("解析 endTime 失败: %v", err)
			return
		}
	} else if len(configStartTime) > 0 && len(configEndTime) > 0 {
		var err error
		startTime, err = time.ParseInLocation(layout, configStartTime, time.Local)
		if err != nil {
			log.Printf("解析 configStartTime 失败: %v", err)
			return
		}
		endTime, err = time.ParseInLocation(layout, configEndTime, time.Local)
		if err != nil {
			log.Printf("解析 configEndTime 失败: %v", err)
			return
		}
	} else {
		// 默认使用前一天的 00:00 到 23:59:59
		yesterday := time.Now().AddDate(0, 0, -1)
		startTime = time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 0, 0, 0, 0, time.Local)
		endTime = time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 23, 59, 59, 0, time.Local)
	}

	s.GetBindUsers(startTime, endTime)
}
